package com.cloud.base.proxy;

import com.cloud.base.annotation.ApiMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

import javax.annotation.PostConstruct;

/**
 * @Author liuyuan
 * @Date 2020-01-15 14:41
 * @Version 1.0
 */
public class DynamicInjectBean implements ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(DynamicInjectBean.class);
    DefaultListableBeanFactory beanFactory = null;
    private String basePackage;
    public void inject(Class classzz) {
        try {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder
                    .genericBeanDefinition(ApiFactory.class);
            beanFactory.registerBeanDefinition(classzz.getName(),
                    builder.getBeanDefinition());
            logger.info("remote 注册"+classzz.getName()+"到Spring容器中...");
        } catch (Exception e) {
            throw new RuntimeException("创建service" + classzz.getSimpleName()
                    + "异常:", e);
        }
    }


    @PostConstruct
    public void init() {
        Class classzz = ApiMapping.class;

        inject(classzz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationcontext)
            throws BeansException {
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationcontext;
        beanFactory = (DefaultListableBeanFactory) configurableApplicationContext
                .getBeanFactory();
    }
}
